<?php

require_once('Image/Canvas.php');
require_once('Image/Graph.php');
require_once(dirname(__FILE__)."/utility.php");

class GraphMaker {

	private static $colorArray = array("#D28181", "#81D2C4", "#ABD281", "#D2B881", "#D281D1");

	public static function generate($queryResult, $dir=null) {

		if ($dir == null)
			$dir = "./";

		if (!endsWith($dir, "/"))
			$dir = $dir."/";

		$graphFile = $dir."".time().".png";

		$Canvas =& Image_Canvas::factory('png', array('width' => 600, 'height' => 400, 'antialias' => 'native'));
		$Graph  =& Image_Graph::factory('graph', $Canvas);

		// add a TrueType font
		$Font =& $Graph->addNew('font', 'Verdana');
		$Font->setSize(6);
		$Graph->setFont($Font);


		$Graph->add(
		    Image_Graph::vertical(
			Image_Graph::factory('title', array($queryResult->title, 10)),
			$Plotarea = Image_Graph::factory('plotarea'),
			10
		    )
		);


		$matrix 	= $queryResult->getMatrix();
		$rowNames	= $queryResult->getRowNames();
		$columnNames	= $queryResult->getColumnNames();

		for ($c=0; $c<sizeof($columnNames); $c++) {

			$Dataset =& Image_Graph::factory('dataset');
			$Dataset->setName($columnNames[$c]);

			for ($r=0; $r<sizeof($rowNames); $r++) {
				$Dataset->addPoint($rowNames[$r], $matrix[$rowNames[$r]][$columnNames[$c]]);
			}

			$Plot =& $Plotarea->addNew('line', $Dataset);


			//Map colors
			$colorCount = sizeof(self::$colorArray);
			$colorPos = $c;
			while ($colorPos >= $colorCount) {
				$colorPos -= $colorCount;
			}


			$LineStyle =& Image_Graph::factory('Image_Graph_Line_Solid', array(self::$colorArray[$colorPos]));
			$LineStyle->setThickness(2);
			$Plot->setLineStyle($LineStyle);
		}

		//$YAxis =& $Plotarea->getAxis(IMAGE_GRAPH_AXIS_Y);
		//$YAxis->setTitle($queryResult->valueLegend, 'vertical');
		$XAxis =& $Plotarea->getAxis(IMAGE_GRAPH_AXIS_X);
		$XAxis->setTitle($queryResult->dataLegend);
		//$XAxis->setFontAngle(-45);
		$XAxis->setLabelInterval(2);

		$Legend =& $Plotarea->addNew('legend');
		$Legend->setFillColor('white@0.7');
		$Legend->setFontSize(8);
		$Legend->showShadow();

		$Graph->done(array('filename' => $graphFile) );

		return $graphFile;

	}

}

?>